package cn.itsource.common;


import cn.itsource.config.CosProperties;
import cn.itsource.constants.RConst;
import cn.itsource.exception.GlobalException;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.InputStream;
import java.util.UUID;



@Data
@Slf4j
public class TxCos {

    private CosProperties cosProperties;

    private COSClient cosClient;

    public TxCos(CosProperties cosProperties, COSClient cosClient) {
        this.cosProperties = cosProperties;
        this.cosClient = cosClient;
    }



    private String resultUrl = "https://%s.cos.%s.myqcloud.com/%s";


    public String uploadFile(InputStream input, ObjectMetadata metadata, String suffix) {
        if(!suffix.startsWith(RConst.Str.DOT)){
            throw new GlobalException("后缀名错误");
        }
        String fileName = UUID.randomUUID().toString();
        String key = cosProperties.getBasePath() + RConst.Str.SLASH + fileName + suffix;
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosProperties.getBucketName(), key, input,metadata);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        log.info(putObjectResult.getDateStr());
        return String.format(resultUrl, cosProperties.getBucketName(), cosProperties.getRegionName(), key);
    }

}
